<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\CompanyAdminModel;

class AuthCompany
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // 判断当前请求是否需要验证
        if (in_array($request->route()->getName(), $this->except)) {
            return $next($request);
        }

        // 获取请求头包含的X-Token， 默认为空字符串
        $token = $request->header('Token', '');
        // 检查X-Token是否为空
        if (!$token) {
            // 如果为空，返回错误信息
            return response()->json(['msg' => '未授权，请先登录', 'code' =>  201], 200);
        }

        // 检查X-Token是否存在于数据库中
        $companyAdmin = CompanyAdminModel::where('token', $token)->first();
        if (!$companyAdmin) {
            // 如果不存在，返回错误信息
            return response()->json(['msg' => '非法访问', 'code' => 202 ], 200);
        }

        // 添加一些额外的参数到请求中
        $request->merge(['company_id' => $companyAdmin->company_id, 'company_admin_id' => $companyAdmin->id]);
        return $next($request);
    }

    private $except = [
        'companyLogin',
    ];
}
